package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    public void insert(String keyword, Integer userId) {
        //1. 查询当前的关键字是否存在
        Query query = Query.query(Criteria.where("keyword").is(keyword).and("userId").is(userId));
        ApUserSearch one = mongoTemplate.findOne(query, ApUserSearch.class);

        //2. 如果存在则更新时间
        if(null != one){
            one.setCreatedTime(new Date());
            mongoTemplate.save(one);
            return;
        }

        //3. 如果不存在则查询当前用户的所有的历史记录
        query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);

        //4. 判断历史记录是否达到了10条 如果没有达到则直接插入数据, 如果达到了则替换最老的一行记录
        ApUserSearch userSearch = new ApUserSearch();
        userSearch.setCreatedTime(new Date());
        userSearch.setKeyword(keyword);
        userSearch.setUserId(userId);


        if(null == list || list.size() < 10){
            mongoTemplate.save(userSearch);
        }else{
            //获取最老的搜索记录
            ApUserSearch lastSearch = list.get(list.size() - 1);
            query = Query.query(Criteria.where("id").is(lastSearch.getId()));
            mongoTemplate.findAndReplace(query, userSearch);
        }
    }

    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        ApUser user = AppThreadLocalUtil.getUser();
        if(null == user){
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
        }

        Query query = Query.query(Criteria.where("userId").is(user.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);

        return ResponseResult.okResult(list);
    }

    /**
     * 删除搜索历史
     *
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        if(null == historySearchDto || null ==historySearchDto.getId()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if(null == user){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        Query query = Query.query(Criteria.where("id")
                .is(historySearchDto.getId())
                .and("userId")
                .is(user.getId()));
        mongoTemplate.remove(query, ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
